/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tencent.tendon.convert.json;

import com.tencent.tendon.convert.util.Poolable;
import com.tencent.tendon.convert.util.Utility;

/**
 *
 * @author nbzhang
 */
public final class JsonDefaultWriter extends JsonWriter implements Poolable {

	private static final int defaultSize = Integer.parseInt(System.getProperty("DefaultSize." + JsonDefaultWriter.class.getSimpleName(), "128"));

	private char[] content;

	public JsonDefaultWriter() {
		this(defaultSize);
	}

	public JsonDefaultWriter(int size) {
		this.content = new char[size > 32 ? size : 32];
	}

	//-----------------------------------------------------------------------
	@Override
	public char[] expand(int len) {
		int newcount = count + len;
		if (newcount <= content.length) return content;
		char[] newdata = new char[Math.max(content.length * 3 / 2, newcount)];
		System.arraycopy(content, 0, newdata, 0, count);
		this.content = newdata;
		return newdata;
	}

	@Override
	public void write(final char ch) {
		expand(1);
		content[count++] = ch;
	}

	@Override
	public void write(final char... chs) {
		int len = chs.length;
		expand(len);
		System.arraycopy(chs, 0, content, count, len);
		count += len;
	}

	@Override
	public void write(final char[] chs, final int start, final int end) {
		int len = end - start;
		expand(len);
		System.arraycopy(chs, start, content, count, len);
		count += len;
	}

	@Override
	public boolean indirect() {
		return false;
	}

	@Override
	public void write(final boolean quote, final String value) {
		int len = value.length();
		expand(len + (quote ? 2 : 0));
		if (quote) content[count++] = '"';
		value.getChars(0, len, content, count);
		count += len;
		if (quote) content[count++] = '"';
	}

	@Override
	public void prepare() {
	}

	@Override
	public void release() {
		super.release();
		if (this.content.length > defaultSize) {
			this.content = new char[defaultSize];
		}
	}

	public char[] toArray() {
		if (count == content.length) return content;
		char[] newdata = new char[count];
		System.arraycopy(content, 0, newdata, 0, count);
		return newdata;
	}

	public byte[] toUTF8Bytes() {
		return Utility.encodeUTF8(content, 0, count);
	}

	@Override
	public String toString() {
		return new String(content, 0, count);
	}
}
